import { Injectable } from '@nestjs/common';
import { find, filter } from 'lodash';
import { Post } from '../models/models';
import { UpvotePostInput } from '../dto/args';
import { FakeSource } from '../fakesource/fakesource';

@Injectable()
export class PostsService {

    fakeSource = FakeSource.getInstance();

    async findPostById(id: number): Promise<Post> {
        const { posts } = this.fakeSource;

        return new Promise((resolve, reject) => {
            resolve(find(posts, (item) => item.id === id));
        });
    }

    async findPostsByAuthorId(authorId: number): Promise<Post[]> {
        const { posts } = this.fakeSource;

        return new Promise((resolve, reject) => {
            const postsByAuthor = filter(posts, (item) => item.author.id === authorId);
            resolve(postsByAuthor);
        });
    }

    // 根据id修改该文章的投票数
    async upvoteById(upvotePostInput: UpvotePostInput): Promise<Post> {
        const post = await this.findPostById(upvotePostInput.id);
        post.votes += upvotePostInput.votes;
        return post;
    }
}